using Microsoft.AspNetCore.Mvc;
using TerritoryGame.Application.Interfaces;
using TerritoryGame.Domain.Entities.App;
using TerritoryGame.Application.Commands;
using TerritoryGame.Application.Dtos;

namespace TerritoryGame.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StatsController : ControllerBase
    {
        private readonly IAppGameStatsService _gameStatsService;
        private readonly IAppGameService _gameService;
        private readonly IAppUserService _userService;

        public StatsController(IAppGameStatsService gameStatsService, IAppGameService gameService, IAppUserService userService)
        {
            _gameStatsService = gameStatsService;
            _gameService = gameService;
            _userService = userService;
        }

        /// <summary>
        /// 获取玩家统计信息
        /// </summary>
        [HttpGet("player/{playerId}")]
        public async Task<ActionResult<ApiResult<object>>> GetPlayerStats(string playerId)
        {
            try
            {
                var stats = await _gameStatsService.GetPlayerStatsAsync(playerId);
                if (stats == null)
                {
                    return NotFound(ApiResult.Failed(404, "玩家统计信息不存在"));
                }

                // 附加头像与更准确的用户名
                string? avatar = null;
                string displayName = string.IsNullOrWhiteSpace(stats.Username) ? "Unknown" : stats.Username;
                if (Guid.TryParse(playerId, out var pid))
                {
                    var userRes = await _userService.GetUserByIdAsync(pid);
                    if (userRes != null && userRes.Data is UserListDto userDto)
                    {
                        avatar = userDto.Avatar;
                        displayName = string.IsNullOrWhiteSpace(displayName) ? userDto.UserName : displayName;
                    }
                }

                var payload = new
                {
                    playerId = stats.PlayerId,
                    username = displayName,
                    avatar,
                    totalGamesPlayed = stats.TotalGamesPlayed,
                    totalGamesWon = stats.TotalGamesWon,
                    totalAreaPainted = stats.TotalAreaPainted,
                    averageAreaPerGame = stats.AverageAreaPerGame,
                    totalPlayTime = stats.TotalPlayTime,
                    firstGameDate = stats.FirstGameDate,
                    lastGameDate = stats.LastGameDate,
                    currentStreak = stats.CurrentStreak,
                    bestStreak = stats.BestStreak,
                    winRate = stats.WinRate,
                    player = (object?)null,
                    id = stats.Id,
                    isActive = stats.IsActive,
                    isDeleted = stats.IsDeleted,
                    createdAt = stats.CreatedAt,
                    updatedAt = stats.UpdatedAt
                };

                return Ok(ApiResult.Success("获取玩家统计信息成功", payload));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取玩家统计信息失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取房间统计信息
        /// </summary>
        [HttpGet("room/{roomId}")]
        public async Task<ActionResult<ApiResult<RoomStats>>> GetRoomStats(string roomId)
        {
            try
            {
                var stats = await _gameStatsService.GetRoomStatsAsync(roomId);
                if (stats == null)
                {
                    return NotFound(ApiResult.Failed(404, "房间统计信息不存在"));
                }
                return Ok(ApiResult.Success("获取房间统计信息成功", stats));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取房间统计信息失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取全局统计信息
        /// </summary>
        [HttpGet("global")]
        public async Task<ActionResult<ApiResult<GlobalStats>>> GetGlobalStats()
        {
            try
            {
                var stats = await _gameStatsService.GetGlobalStatsAsync();
                if (stats == null)
                {
                    return NotFound(ApiResult.Failed(404, "全局统计信息不存在"));
                }
                return Ok(ApiResult.Success("获取全局统计信息成功", stats));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取全局统计信息失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取排行榜
        /// </summary>
        [HttpGet("leaderboard")]
        public async Task<ActionResult<ApiResult<List<LeaderboardEntry>>>> GetLeaderboard([FromQuery] int top = 10)
        {
            try
            {
                if (top <= 0 || top > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "排行榜数量必须在1-100之间"));
                }

                var leaderboard = await _gameStatsService.GetLeaderboardAsync(top);
                return Ok(ApiResult.Success("获取排行榜成功", leaderboard));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取排行榜失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 按分类获取排行榜
        /// </summary>
        [HttpGet("leaderboard/{category}")]
        public async Task<ActionResult<ApiResult<List<LeaderboardEntry>>>> GetLeaderboardByCategory(
            string category, 
            [FromQuery] int top = 10)
        {
            try
            {
                if (top <= 0 || top > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "排行榜数量必须在1-100之间"));
                }

                var validCategories = new[] { "wins", "winrate", "area", "streak" };
                if (!validCategories.Contains(category.ToLower()))
                {
                    return BadRequest(ApiResult.Failed(400, "无效的分类，支持：wins, winrate, area, streak"));
                }

                var leaderboard = await _gameStatsService.GetLeaderboardByCategoryAsync(category, top);
                return Ok(ApiResult.Success("获取分类排行榜成功", leaderboard));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取分类排行榜失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取顶级玩家
        /// </summary>
        [HttpGet("top-players")]
        public async Task<ActionResult<ApiResult<List<PlayerStats>>>> GetTopPlayers([FromQuery] int top = 10)
        {
            try
            {
                if (top <= 0 || top > 100)
                {
                    return BadRequest(ApiResult.Failed(400, "玩家数量必须在1-100之间"));
                }

                var topPlayers = await _gameStatsService.GetTopPlayersAsync(top);
                return Ok(ApiResult.Success("获取顶级玩家成功", topPlayers));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取顶级玩家失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取房间排行榜
        /// </summary>
        [HttpGet("room/{roomId}/leaderboard")]
        public async Task<ActionResult<ApiResult<List<RoomLeaderboardEntry>>>> GetRoomLeaderboard(string roomId)
        {
            try
            {
                if (string.IsNullOrEmpty(roomId))
                {
                    return BadRequest(ApiResult.Failed(400, "房间ID不能为空"));
                }

                var leaderboard = await _gameService.GetRoomLeaderboardAsync(roomId);
                return Ok(ApiResult.Success("获取房间排行榜成功", leaderboard));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResult.Failed(500, $"获取房间排行榜失败: {ex.Message}"));
            }
        }
    }
}
